package com.lizard.schedule.widget;

import com.lizard.schedule.log.ScheduleLog;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.ObjectAnimator;

import android.content.Context;
import android.graphics.PixelFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.lizard.schedule.ScheduleApplication;
import com.lizard.schedule.R;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Schedule自定义风格的Toast
 */
public class ScheduleToast {

    private static final String TAG = ScheduleLog.class.getSimpleName();

    private static final long DURATION_SHORT = 2000;

    private static final long DURATION_LONG = 3500;

    /**
     * 显示/隐藏渐隐效果动画时间
     */
    private static final long ALPHA_ANIM_DURATION = 100;

    /**
     * log开关
     */
    private static boolean logAble = true;

    /**
     * ScheduleToast全局任务队列
     */
    private static Queue<ScheduleToast> scheduleToastQueue = new LinkedBlockingQueue<ScheduleToast>();

    private static WindowManager wm;

    private static WindowManager.LayoutParams wmParams;

    private static View wmView;

    private static TextView textTv;

    private static View scheduleToastContent;

    /**
     * 显示动画
     */
    private static Animator showAnim;

    /**
     * 隐藏动画
     */
    private static Animator hideAnim;

    /**
     * wm等相关界面动画等是否已经初始化
     */
    private static boolean wmInited = false;

    /**
     * 显示文字内容
     */
    private String mText;

    /**
     * 持续时间
     */
    private long mDuration;

    private ScheduleToast mScheduleToast;

    private ScheduleToast() {
    }

    /**
     * 生成ScheduleToast对象(持续时间短)
     *
     * @param text
     * @return
     */
    public static ScheduleToast makeScheduleToastS(String text) {
        ScheduleToast scheduleToast = new ScheduleToast();

        scheduleToast.setText(text);
        scheduleToast.mScheduleToast = scheduleToast;
        scheduleToast.mDuration = DURATION_SHORT;

        return scheduleToast;
    }

    /**
     * 生成ScheduleToast对象(持续时间短)
     *
     * @param textId
     * @return
     */
    public static ScheduleToast makeScheduleToastS(int textId) {
        return makeScheduleToastS(ScheduleApplication.applicationContext.getString(textId));
    }

    /**
     * 生成ScheduleToast对象(持续时间长)
     *
     * @param text
     * @return
     */
    public static ScheduleToast makeScheduleToastL(String text) {
        ScheduleToast scheduleToast = new ScheduleToast();

        scheduleToast.setText(text);
        scheduleToast.mScheduleToast = scheduleToast;
        scheduleToast.mDuration = DURATION_LONG;

        return scheduleToast;
    }

    /**
     * 生成ScheduleToast对象(持续时间长)
     *
     * @param resId
     * @return
     */
    public static ScheduleToast makeScheduleToastL(int resId) {
        return makeScheduleToastL(ScheduleApplication.applicationContext.getString(resId));
    }

    /**
     * 设置显示的文字内容
     *
     * @param text
     */
    public void setText(String text) {
        mText = text;
    }

    /**
     * 将任务放入队列执行
     */
    public void show() {

        ScheduleApplication.handler.post(new Runnable() {

            @Override
            public void run() {
                synchronized (scheduleToastQueue) {

                    scheduleToastQueue.add(mScheduleToast);
                    if (!wmInited || wmView.getParent() == null) { // is not showing
                        pull();
                    }

                }
            }

        });

    }

    /**
     * 结束所有ScheduleToast
     */
    public static void cancelAll() {
        ScheduleApplication.handler.post(new Runnable() {

            @Override
            public void run() {
                synchronized (scheduleToastQueue) {

                    scheduleToastQueue.clear();

                    animRemoveWmContent();

                }
            }

        });

    }

    /**
     * 从队列拉取任务并执行
     */
    private static void pull() {

        init();

        ScheduleToast scheduleToast = scheduleToastQueue.poll();

        if (logAble) {
            ScheduleLog.v(TAG, "scheduleToastQueue size:" + scheduleToastQueue.size());
        }

        if (scheduleToast == null) {

            animRemoveWmContent();

        } else {

            textTv.setText(scheduleToast.mText);

            animAddWmContent();

            ScheduleApplication.handler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    pull();
                }

            }, scheduleToast.mDuration);


        }

    }

    /**
     * 添加wm里面的内容(附带动画效果)
     */
    private static void animAddWmContent() {
        if (wmInited && wmView.getParent() == null) {

            wm.addView(wmView, wmParams);
            showAnim.start();

        }
    }

    /**
     * 移除wm里面的内容(附带动画效果)
     */
    private static void animRemoveWmContent() {

        if (wmInited && wmView.getParent() != null && !hideAnim.isRunning()) {
            hideAnim.start();
        }

    }

    /**
     * 移除wm里面的内容
     */
    private static void removeWnContent() {
        if (wmInited && wmView.getParent() != null) {

            try {
                wm.removeView(wmView);
            } catch (Exception e) {

            }

        }
    }

    private static void init() {
        if (!wmInited) {

            wmParams = new WindowManager.LayoutParams();
            wmParams.type = WindowManager.LayoutParams.TYPE_TOAST;
            wmParams.format = PixelFormat.TRANSPARENT;
            wmParams.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                    | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                    | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
            wmParams.setTitle("Schedule Toast");
            int width = (int) ScheduleApplication.applicationContext.getResources().getDimension(R.dimen.schedule_toast_width); // 宽高
            wmParams.width = width;
            wmParams.height = width;

            wm = (WindowManager) ScheduleApplication.applicationContext.getSystemService(Context.WINDOW_SERVICE);

            wmView = LayoutInflater.from(ScheduleApplication.applicationContext).inflate(R.layout.schedule_toast, null);

            scheduleToastContent = wmView.findViewById(R.id.schedule_toast_content);

            textTv = (TextView) wmView.findViewById(R.id.text);

            showAnim = ObjectAnimator.ofFloat(scheduleToastContent, "alpha", 0, 1).setDuration(ALPHA_ANIM_DURATION);

            hideAnim = ObjectAnimator.ofFloat(scheduleToastContent, "alpha", 1, 0).setDuration(ALPHA_ANIM_DURATION);
            hideAnim.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animator) {

                }

                @Override
                public void onAnimationEnd(Animator animator) {
                    removeWnContent();
                }

                @Override
                public void onAnimationCancel(Animator animator) {
                    removeWnContent();
                }

                @Override
                public void onAnimationRepeat(Animator animator) {

                }
            });

            wmInited = true; // 标记为初始化成功
        }
    }

}
